package com.iflytek.autofly.setting.biz.voice;

import android.content.Context;
import android.os.SystemProperties;

import com.iflytek.autofly.setting.R;
import com.iflytek.autofly.utils.FlyLog;

public class SpeakerConfig {
    private static final String SPEAKER_PROPERTY = "persist.sys.autofly.speaker";
    private static final int DEFAULT_SPEAKER = 99;
    private static final String TAG = "SpeakerConfig";
    private Context mContext;
    private int[] mSpeakerIds;
    private String[] mSpeakers;
    private String[] mSpeakersWithDesc;
    private int mLength;
    private SpeakerConfig() {

    }

    public static SpeakerConfig getInstance(Context ctx) {
        SpeakerConfig inst = SpeakerConfigInstance.INSTANCE;
        inst.setContext(ctx);
        return inst;
    }

    private void setContext(Context ctx) {
        if (mContext == null) {
            mContext = ctx;

            mSpeakerIds = mContext.getResources().getIntArray(
                    R.array.voice_speaker_ids);
            mSpeakers = mContext.getResources().getStringArray(
                    R.array.voice_speaker_names);
            mSpeakersWithDesc = mContext.getResources().getStringArray(
                    R.array.voice_speaker_names_with_desc);
            mLength = mSpeakers.length;
            if (mSpeakers.length != mSpeakerIds.length) {
                FlyLog.e(TAG, "resource error mSpeakers.length="
                        + mSpeakers.length + " mSpeakerIds.length="
                        + mSpeakerIds.length);
                mLength = Math.min(mSpeakers.length, mSpeakerIds.length);
            }
        }
    }

    public void setSpeakerAt(int index) {
        setSpeakerId(mSpeakerIds[index]);
    }

    public String getSpeakerAt(int index) {
        return mSpeakers[index];
    }

    public String getSpeakerWithDescAt(int index) {
        return mSpeakersWithDesc[index];
    }

    public int getSpeakerIdAt(int index) {
        return mSpeakerIds[index];
    }

    public int getSpeakerId() {
        return SystemProperties.getInt(SPEAKER_PROPERTY, DEFAULT_SPEAKER);
    }

    public void setSpeakerId(int id) {
        SystemProperties.set(SPEAKER_PROPERTY, Integer.toString(id));
    }

    public String getSpeaker() {
        int id = getSpeakerId();
        for (int i = 0; i < mLength; i++) {
            if (id == mSpeakerIds[i]) {
                return mSpeakers[i];
            }
        }
        return "";
    }

    public int getSpeakerCount() {
        return mLength;
    }

    public int getSpeakerPosition() {
        int id = getSpeakerId();
        for (int i = 0; i < mLength; i++) {
            if (id == mSpeakerIds[i]) {
                return i;
            }
        }
        return 0;
    }

    private static class SpeakerConfigInstance {
        private static final SpeakerConfig INSTANCE = new SpeakerConfig();
    }

}
